<!--
  团队成员邀请对话框组件

  功能说明：
  1. 好友邀请：从联系人模块选择好友进行邀请，邀请的好友只能获得成员权限
  2. 邀请码邀请：通过邀请码邀请外部用户加入团队

  安全特性：
  - 好友邀请固定为成员(MEMBER)权限，不能邀请为管理员
  - 自动排除已经是团队成员的好友，避免重复邀请
  - 支持批量邀请多个好友

  用户体验：
  - 支持好友搜索过滤（姓名、用户名、备注）
  - 多选好友进行批量操作
  - 无好友时引导用户去添加好友
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('team.inviteMembers')"
    width="700px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="invite-content">
      <!-- 邀请方式选择 -->
      <div class="invite-methods">
        <el-radio-group v-model="inviteMethod" @change="handleMethodChange">
          <el-radio label="friends">邀请好友</el-radio>
          <el-radio label="inviteCode">{{ $t('team.inviteByCode') }}</el-radio>
        </el-radio-group>
      </div>

      <!-- 通过好友邀请 -->
      <div v-if="inviteMethod === 'friends'" class="friends-invite-section">
        <!-- 搜索好友 -->
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索好友..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 好友列表 -->
        <div class="friends-list" v-loading="contactsStore.loading">
          <div v-if="filteredFriends.length === 0" class="empty-state">
            <el-empty description="暂无可邀请的好友">
              <el-button type="primary" @click="goToContacts">
                去添加好友
              </el-button>
            </el-empty>
          </div>

          <div v-else class="friend-items">
            <div
              v-for="friend in filteredFriends"
              :key="friend.relationshipId"
              class="friend-item"
              :class="{ selected: selectedFriends.includes(friend.userId) }"
              @click="toggleFriend(friend)"
            >
              <div class="friend-avatar">
                <el-avatar :src="friend.avatarUrl" :size="40">
                  {{ friend.realName?.charAt(0) || friend.username.charAt(0) }}
                </el-avatar>
              </div>

              <div class="friend-info">
                <div class="friend-name">
                  {{ friend.realName || friend.username }}
                  <el-tag v-if="friend.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
                  <el-tag v-if="friend.userType === 'ADMIN'" type="danger" size="small">管理员</el-tag>
                </div>
                <div class="friend-details">
                  <span class="username">@{{ friend.username }}</span>
                  <span v-if="friend.remark" class="remark">{{ friend.remark }}</span>
                </div>
              </div>

              <div class="friend-actions">
                <el-checkbox
                  :model-value="selectedFriends.includes(friend.userId)"
                  @change="toggleFriend(friend)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 已选择的好友 -->
        <div v-if="selectedFriends.length > 0" class="selected-friends">
          <h4>已选择 {{ selectedFriends.length }} 位好友</h4>
          <div class="selected-list">
            <el-tag
              v-for="friendId in selectedFriends"
              :key="friendId"
              closable
              @close="removeFriend(friendId)"
            >
              {{ getFriendName(friendId) }}
            </el-tag>
          </div>
        </div>

        <el-alert
          title="好友邀请说明"
          type="info"
          :closable="false"
          show-icon
        >
          从您的好友列表中选择要邀请的好友，邀请的好友将以成员身份加入团队
        </el-alert>
      </div>

      <!-- 通过邀请码邀请 -->
      <div v-else-if="inviteMethod === 'inviteCode'" class="code-invite-section">
        <div class="active-codes" v-if="activeCodes.length > 0">
          <h4>{{ $t('team.activeInviteCodes') }}</h4>
          <div class="code-list">
            <div 
              v-for="code in activeCodes" 
              :key="code.id"
              class="code-item"
            >
              <div class="code-info">
                <div class="code-value">
                  <el-icon><Key /></el-icon>
                  <span class="code-text">{{ code.inviteCode }}</span>
                  <el-button 
                    type="text" 
                    size="small"
                    :icon="CopyDocument"
                    @click="copyCode(code.inviteCode)"
                  >
                    {{ $t('common.copy') }}
                  </el-button>
                </div>
                <div class="code-meta">
                  <el-tag :type="getMemberRoleType(code.inviteRole)" size="small">
                    {{ getMemberRoleLabel(code.inviteRole) }}
                  </el-tag>
                  <span class="usage-info" v-if="code.maxUses">
                    {{ code.usedCount }}/{{ code.maxUses }}
                  </span>
                  <span class="expire-info" v-if="code.expireTime">
                    {{ $t('team.expiresAt') }} {{ formatDate(code.expireTime) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="no-codes">
          <el-empty :description="$t('team.noActiveInviteCodes')" :image-size="80">
            <el-button 
              type="primary" 
              @click="showGenerateDialog = true"
            >
              {{ $t('team.generateFirstCode') }}
            </el-button>
          </el-empty>
        </div>

        <el-alert
          :title="$t('team.codeInviteTip')"
          type="info"
          :closable="false"
          show-icon
          style="margin-top: 16px"
        >
          {{ $t('team.codeInviteTipDesc') }}
        </el-alert>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button
          v-if="inviteMethod === 'friends'"
          type="primary"
          @click="handleInviteFriends"
          :loading="loading"
          :disabled="selectedFriends.length === 0"
        >
          邀请好友 ({{ selectedFriends.length }})
        </el-button>
        <el-button
          v-else
          type="primary"
          @click="showGenerateDialog = true"
        >
          {{ $t('team.generateNewCode') }}
        </el-button>
      </div>
    </template>

    <!-- 生成邀请码对话框 -->
    <GenerateInviteCodeDialog
      v-model="showGenerateDialog"
      :team-id="teamId"
      @success="handleGenerateSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Key, CopyDocument, Search } from '@element-plus/icons-vue'
import { useTeamStore } from '@/stores/teamStore'
import { useContactsStore } from '@/stores/contacts'
import type { AddMemberRequest } from '@/types/team'
import { getMemberRoleLabel, getMemberRoleType } from '@/types/team'
import { formatDate } from '@/utils/date'
import GenerateInviteCodeDialog from './GenerateInviteCodeDialog.vue'

// 导入联系人API类型
interface Friend {
  userId: number
  username: string
  realName?: string
  avatarUrl?: string
  remark?: string
  groupName: string
  relationshipId: number
  userType?: string
  isOnline?: boolean
}

interface Props {
  modelValue: boolean
  teamId: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()
const router = useRouter()

const teamStore = useTeamStore()
const contactsStore = useContactsStore()
const formRef = ref<FormInstance>()
const loading = ref(false)
const inviteMethod = ref('friends')
const showGenerateDialog = ref(false)

// 好友邀请相关数据
const searchKeyword = ref('')
const selectedFriends = ref<number[]>([])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 活跃的邀请码
const activeCodes = computed(() => teamStore.activeInviteCodes)

/**
 * 过滤后的好友列表
 * 功能：
 * 1. 根据搜索关键词过滤好友（支持姓名、用户名、备注搜索）
 * 2. 排除已经是团队成员的好友，避免重复邀请
 * 3. 返回可邀请的好友列表
 */
const filteredFriends = computed(() => {
  // console.log('🔍 Debug - contactsStore.friends:', contactsStore.friends)
  // console.log('🔍 Debug - teamStore.teamMembers:', teamStore.teamMembers)

  let friends = contactsStore.friends || []

  // 根据搜索关键词过滤好友
  // 支持按真实姓名、用户名、备注进行模糊搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    friends = friends.filter((friend: Friend) =>
      (friend.realName && friend.realName.toLowerCase().includes(keyword)) ||
      friend.username.toLowerCase().includes(keyword) ||
      (friend.remark && friend.remark.toLowerCase().includes(keyword))
    )
  }

  // 排除已经是团队成员的好友
  // 获取当前团队所有成员的用户ID列表，避免重复邀请
  const memberUserIds = (teamStore.teamMembers || []).map(member => member.userId)
  // console.log('🔍 Debug - memberUserIds:', memberUserIds)
  // console.log('🔍 Debug - friends before filter:', friends.map(f => ({ userId: f.userId, username: f.username })))

  friends = friends.filter((friend: Friend) => {
    const isNotMember = !memberUserIds.includes(friend.userId)
    // console.log(`🔍 Debug - friend ${friend.username} (${friend.userId}): isNotMember=${isNotMember}`)
    return isNotMember
  })

  // console.log('🔍 Debug - filteredFriends:', friends)
  return friends
})

/**
 * 邀请方式切换处理
 * 当用户在"邀请好友"和"邀请码"之间切换时，重置相关状态
 */
const handleMethodChange = () => {
  // 切换邀请方式时重置状态，避免数据混乱
  selectedFriends.value = []
  searchKeyword.value = ''
}

/**
 * 搜索输入处理
 * 由于使用computed进行本地过滤，这里不需要防抖处理
 */
const handleSearch = () => {
  // 本地过滤，无需额外处理
}

/**
 * 切换好友选择状态
 * 支持多选好友进行批量邀请
 * @param friend 要切换选择状态的好友对象
 */
const toggleFriend = (friend: Friend) => {
  const index = selectedFriends.value.indexOf(friend.userId)
  if (index > -1) {
    // 如果已选中，则取消选择
    selectedFriends.value.splice(index, 1)
  } else {
    // 如果未选中，则添加到选择列表
    selectedFriends.value.push(friend.userId)
  }
}

/**
 * 从已选择列表中移除好友
 * 用于已选择好友标签的删除操作
 * @param friendId 要移除的好友用户ID
 */
const removeFriend = (friendId: number) => {
  const index = selectedFriends.value.indexOf(friendId)
  if (index > -1) {
    selectedFriends.value.splice(index, 1)
  }
}

/**
 * 获取好友显示名称
 * 优先显示真实姓名，其次显示用户名
 * @param friendId 好友用户ID
 * @returns 好友显示名称
 */
const getFriendName = (friendId: number) => {
  const friend = contactsStore.friends.find((f: Friend) => f.userId === friendId)
  return friend ? (friend.realName || friend.username) : `用户${friendId}`
}

/**
 * 邀请选中的好友加入团队
 * 核心功能：批量邀请好友，固定为成员权限，确保安全性
 */
const handleInviteFriends = async () => {
  // 验证是否选择了好友
  if (selectedFriends.value.length === 0) {
    ElMessage.warning('请选择要邀请的好友')
    return
  }

  try {
    // 确认邀请操作
    await ElMessageBox.confirm(
      `确定要邀请 ${selectedFriends.value.length} 位好友加入团队吗？`,
      '确认邀请',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    loading.value = true

    // 批量邀请好友
    // 重要：所有通过好友邀请的用户只能获得成员(MEMBER)权限，不能是管理员
    // 这是为了确保团队安全，防止权限滥用
    const promises = selectedFriends.value.map(userId =>
      teamStore.addTeamMember(props.teamId, {
        userId,
        role: 'MEMBER' // 固定为成员权限，不可修改
      })
    )

    // 等待所有邀请完成
    await Promise.all(promises)

    ElMessage.success(`成功邀请 ${selectedFriends.value.length} 位好友加入团队`)
    emit('success') // 通知父组件刷新数据
    resetForm() // 重置表单状态
  } catch (error: any) {
    // 处理用户取消操作
    if (error !== 'cancel') {
      console.error('邀请好友失败:', error)
      ElMessage.error('邀请好友失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 跳转到联系人页面
 * 当用户没有好友时，引导用户去添加好友
 */
const goToContacts = () => {
  router.push('/dashboard/contacts')
  handleClose()
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  selectedFriends.value = []
  searchKeyword.value = ''
}

const copyCode = async (code: string) => {
  try {
    await navigator.clipboard.writeText(code)
    ElMessage.success(t('team.copySuccess'))
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = code
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success(t('team.copySuccess'))
  }
}

const handleGenerateSuccess = () => {
  showGenerateDialog.value = false
  ElMessage.success(t('team.generateSuccess'))
}

const loadInviteCodes = async () => {
  try {
    await teamStore.fetchTeamInviteCodes(props.teamId)
  } catch (error) {
    console.error('加载邀请码失败:', error)
  }
}

/**
 * 加载用户的好友列表
 * 从联系人模块获取好友数据，用于邀请功能
 */
const loadFriends = async () => {
  try {
    // console.log('🔄 开始加载好友列表...')
    await contactsStore.getFriendsList()
    // console.log('✅ 好友列表加载完成:', contactsStore.friends)
  } catch (error) {
    console.error('❌ 加载好友列表失败:', error)
    ElMessage.error('加载好友列表失败，请重试')
  }
}

/**
 * 监听对话框打开状态
 * 当对话框打开时，初始化所需的数据
 */
watch(dialogVisible, async (visible) => {
  if (visible) {
    // console.log('🔄 对话框打开，开始初始化数据...')
    resetForm() // 重置表单状态
    loadInviteCodes() // 加载邀请码列表

    try {
      // 加载团队成员列表，用于过滤已加入的好友
      // console.log('🔄 加载团队成员列表...')
      await teamStore.fetchTeamMembers(props.teamId)
      // console.log('✅ 团队成员列表加载完成')

      // 加载用户的好友列表，用于邀请功能
      // console.log('🔄 加载好友列表...')
      await loadFriends()
      // console.log('✅ 好友列表加载完成')
    } catch (error) {
      console.error('❌ 初始化数据失败:', error)
    }
  }
})
</script>

<style scoped lang="scss">
.invite-content {
  .invite-methods {
    margin-bottom: 24px;
    padding: 16px;
    background: var(--el-bg-color-page);
    border-radius: 8px;
  }

  .friends-invite-section {
    .search-section {
      margin-bottom: 16px;
    }

    .friends-list {
      max-height: 400px;
      overflow-y: auto;
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      background: var(--el-bg-color);

      .empty-state {
        padding: 40px 20px;
        text-align: center;
      }

      .friend-items {
        .friend-item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 12px 16px;
          border-bottom: 1px solid var(--el-border-color-lighter);
          cursor: pointer;
          transition: all 0.2s;

          &:hover {
            background: var(--el-fill-color-light);
          }

          &.selected {
            background: var(--el-color-primary-light-9);
            border-color: var(--el-color-primary-light-7);
          }

          &:last-child {
            border-bottom: none;
          }

          .friend-avatar {
            flex-shrink: 0;
          }

          .friend-info {
            flex: 1;
            min-width: 0;

            .friend-name {
              display: flex;
              align-items: center;
              gap: 8px;
              font-size: 14px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
            }

            .friend-details {
              display: flex;
              align-items: center;
              gap: 12px;
              font-size: 12px;
              color: var(--el-text-color-regular);

              .username {
                color: var(--el-text-color-placeholder);
              }

              .remark {
                color: var(--el-color-primary);
              }
            }
          }

          .friend-actions {
            flex-shrink: 0;
          }
        }
      }
    }

    .selected-friends {
      margin-top: 16px;
      padding: 16px;
      background: var(--el-bg-color-page);
      border-radius: 8px;

      h4 {
        margin: 0 0 12px 0;
        font-size: 14px;
        color: var(--el-text-color-primary);
      }

      .selected-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }
    }
  }

  .code-invite-section {
    .active-codes {
      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        color: var(--el-text-color-primary);
      }

      .code-list {
        .code-item {
          padding: 16px;
          background: var(--el-bg-color-page);
          border-radius: 8px;
          border: 1px solid var(--el-border-color-lighter);
          margin-bottom: 12px;

          .code-info {
            .code-value {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 8px;

              .el-icon {
                color: var(--el-color-primary);
              }

              .code-text {
                font-family: monospace;
                font-size: 16px;
                font-weight: 600;
                color: var(--el-text-color-primary);
                background: var(--el-bg-color);
                padding: 4px 8px;
                border-radius: 4px;
                border: 1px solid var(--el-border-color);
              }
            }

            .code-meta {
              display: flex;
              align-items: center;
              gap: 12px;
              font-size: 12px;

              .usage-info,
              .expire-info {
                color: var(--el-text-color-secondary);
              }
            }
          }
        }
      }
    }

    .no-codes {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 200px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }

  .invite-content {
    .code-invite-section {
      .active-codes {
        .code-list {
          .code-item {
            .code-info {
              .code-value {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
              }

              .code-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
